<template>
  <div class="app-container">
    <el-form ref="questionForm" :model="question" :rules="rules" label-width="120px">
      <el-form-item label="题目类型">
        <el-select v-model="question.questionType" placeholder="请选择题目类型" @change="handleQuestionTypeChange">
          <el-option
            v-for="item in questionTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="课程类别" prop="courseId">
        <el-cascader
          v-model="courseIdS"
          placeholder="试试搜索：java"
          expand-trigger="hover"
          :options="courseList"
          :props="defaultProps"
          filterable
          @change="handleCourseChange">
        </el-cascader>
      </el-form-item>

      <el-form-item label="课程" prop="chapterId">
        <el-select v-model="question.chapterId" placeholder="请选择章节">
          <el-option
            v-for="chapter in chapterList"
            :key="chapter.id"
            :label="chapter.title"
            :value="chapter.id">            
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="题目标题" prop="title">
        <el-input v-model="question.title" placeholder="请输入题目标题"/>
      </el-form-item>

      <el-form-item label="题目内容">
        <el-input
          v-model="question.content"
          type="textarea"
          :rows="4"
          placeholder="请输入题目内容"/>
      </el-form-item>

      <div v-if="question.questionType === 1 || question.questionType === 2">
        <el-form-item label="选项A">
          <el-input v-model="question.optionA" placeholder="请输入选项A内容"/>
        </el-form-item>

        <el-form-item label="选项B">
          <el-input v-model="question.optionB" placeholder="请输入选项B内容"/>
        </el-form-item>

        <el-form-item label="选项C">
          <el-input v-model="question.optionC" placeholder="请输入选项C内容"/>
        </el-form-item>

        <el-form-item label="选项D">
          <el-input v-model="question.optionD" placeholder="请输入选项D内容"/>
        </el-form-item>

        <el-form-item label="选项E" v-if="showOptionE">
          <el-input v-model="question.optionE" placeholder="请输入选项E内容"/>
          <el-button @click="showOptionE = false" type="text">删除选项E</el-button>
        </el-form-item>

        <el-form-item label="选项F" v-if="showOptionF">
          <el-input v-model="question.optionF" placeholder="请输入选项F内容"/>
          <el-button @click="showOptionF = false" type="text">删除选项F</el-button>
        </el-form-item>

        <el-form-item v-if="!showOptionE">
          <el-button @click="showOptionE = true" type="primary" plain>添加选项E</el-button>
        </el-form-item>

        <el-form-item v-else-if="!showOptionF && showOptionE">
          <el-button @click="showOptionF = true" type="primary" plain>添加选项F</el-button>
        </el-form-item>
      </div>

      <el-form-item label="正确答案" prop="answer">
        <div v-if="question.questionType === 1">
          <!-- 单选题 -->
          <el-radio-group v-model="question.answer">
            <el-radio label="A">A</el-radio>
            <el-radio label="B">B</el-radio>
            <el-radio label="C">C</el-radio>
            <el-radio label="D">D</el-radio>
            <el-radio v-if="showOptionE" label="E">E</el-radio>
            <el-radio v-if="showOptionF" label="F">F</el-radio>
          </el-radio-group>
        </div>
        <div v-else-if="question.questionType === 2">
          <!-- 多选题 -->
          <el-checkbox-group v-model="question.answerList">
            <el-checkbox label="A">A</el-checkbox>
            <el-checkbox label="B">B</el-checkbox>
            <el-checkbox label="C">C</el-checkbox>
            <el-checkbox label="D">D</el-checkbox>
            <el-checkbox v-if="showOptionE" label="E">E</el-checkbox>
            <el-checkbox v-if="showOptionF" label="F">F</el-checkbox>
          </el-checkbox-group>
        </div>
        <div v-else-if="question.questionType === 3">
          <!-- 判断题 -->
          <el-radio-group v-model="question.answer">
            <el-radio label="正确">正确</el-radio>
            <el-radio label="错误">错误</el-radio>
          </el-radio-group>
        </div>
        <div v-else-if="question.questionType === 4">
          <!-- 填空题 -->
          <el-input v-model="question.answer" placeholder="请输入正确答案"/>
        </div>
        <div v-else-if="question.questionType === 5">
          <!-- 简答题 -->
          <el-input
            v-model="question.answer"
            type="textarea"
            :rows="4"
            placeholder="请输入参考答案"/>
        </div>
      </el-form-item>

      <el-form-item label="难度等级">
        <el-select v-model="question.level" placeholder="请选择难度等级">
          <el-option label="简单" :value="1"></el-option>
          <el-option label="一般" :value="2"></el-option>
          <el-option label="困难" :value="3"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="答案解析">
        <el-input
          v-model="question.analysis"
          type="textarea"
          :rows="4"
          placeholder="请输入答案解析"/>
      </el-form-item>

      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import questionApi from '@/api/edu/question'
  import courseApi from '@/api/edu/course'
  import subjectApi from '@/api/edu/subject'
  import chapterApi from '@/api/edu/chapter'

  const defaultQuestion = {
    questionType: 1,
    courseId: '',
    chapterId: '',
    title: '',
    content: '',
    optionA: '',
    optionB: '',
    optionC: '',
    optionD: '',
    optionE: '',
    optionF: '',
    answer: '',
    answerList: [],
    level: 1,
    analysis: ''
  }

  export default {
    data() {
      return {
        saveBtnDisabled: false,
        question: defaultQuestion,
        courseIdS: [], // 用于级联选择器的课程ID数组
        courseList: [], // 课程列表
        chapterList: [], // 章节列表
        showOptionE: false,
        showOptionF: false,
        defaultProps: {
          children: 'children',
          label: 'title',
          value: 'id'
        },
        questionTypeOptions: [
          { value: 1, label: '单选题' },
          { value: 2, label: '多选题' },
          { value: 3, label: '判断题' },
          { value: 4, label: '填空题' },
          { value: 5, label: '简答题' }
        ],
        rules: {
          courseId: [{ required: true, trigger: 'change', message: '请选择课程' }],
          chapterId: [{ required: true, trigger: 'change', message: '请选择章节' }],
          title: [{ required: true, trigger: 'blur', message: '题目标题不能为空' }],
          answer: [{ required: true, trigger: 'blur', message: '正确答案不能为空' }]
        }
      }
    },

    created() {
      this.init()
    },

    watch: {
      $route(to, from) {
        this.init()
      }
    },

    methods: {
      // 初始化数据
      init() {
        if (this.$route.params && this.$route.params.id) {
          const id = this.$route.params.id
          // 确保先获取课程分类列表，再获取题目详情
          this.initSubjectList().then(() => {
            this.fetchQuestionById(id)
          })
        } else {
          this.initSubjectList()
          this.question = { ...defaultQuestion }
          this.courseIdS = []
          this.chapterList = []
        }
      },

      // 获取课程分类列表
      initSubjectList() {
        return subjectApi.getNestedTreeList().then(response => {
          this.courseList = response.data
        })
      },

      // 获取章节列表
      handleCourseChange(value) {
        if (value && value.length > 0) {
          // 获取选中的课程分类ID
          const selectedCourseId = value[value.length - 1]
          this.question.courseId = selectedCourseId
          
          // 获取课程列表以获取课程ID
          this.fetchCourseList(value)
        } else {
          this.question.courseId = ''
          this.chapterList = []
        }
        this.question.chapterId = ''
      },

      // 根据课程分类获取课程列表
      fetchCourseList(subjectIds) {
        const subjectParentId = subjectIds[0];
        const subjectId = subjectIds.length > 1 ? subjectIds[1] : '';
        
        // 使用最大整数值作为分页参数
        const maxIntValue = 2147483647;
        
        const searchParams = {
          subjectParentId: subjectParentId,
          subjectId: subjectId,
          title: '',
          teacherId: ''
        };
        
        courseApi.getPageList(1, maxIntValue, searchParams).then(response => {
          this.chapterList = response.data.rows;
        });
      },
      // 根据题目ID获取题目信息
      fetchQuestionById(id) {
        questionApi.getById(id).then(response => {
          this.question = response.data.item
          
          // 处理课程ID回显
          if (this.question.courseId) {
            ////debugger
            // 根据课程ID查找对应的一级和二级分类ID
            this.setCourseCascaderValue(this.question.courseId);
          }
          
          // 处理多选题答案回显
          if (this.question.questionType === 2 && this.question.answer) {
            this.question.answerList = this.question.answer.split(',')
          }
          
          // 处理选项E和F的显示
          if (this.question.optionE) {
            this.showOptionE = true
          }
          if (this.question.optionF) {
            this.showOptionF = true
          }
        })
      },

      // 根据课程ID设置级联选择器的值
      setCourseCascaderValue(courseId) {
        // 遍历courseList查找对应的课程分类路径
        const findCoursePath = (list, targetId) => {
          for (let i = 0; i < list.length; i++) {
            const item = list[i];
            if (item.id === targetId) {
              // 如果当前节点就是目标节点，且没有children，说明是一级分类
              return [item.id];
            }
            if (item.children && item.children.length > 0) {
              // 如果有子节点，递归查找
              const result = findCoursePath(item.children, targetId);
              if (result) {
                // 如果在子节点中找到了，将当前节点ID加入路径开头
                return [item.id, ...result];
              }
            }
          }
          return null;
        };

        // 查找课程分类路径
        const path = findCoursePath(this.courseList, this.question.courseId);
        if (path) {
          this.courseIdS = path;
          // 同时设置question.courseId为最后一级分类ID
          this.question.courseId = path[path.length - 1];
          // 获取章节列表
          this.fetchCourseList(path);
        }
      },

      // 题目类型变化处理
      handleQuestionTypeChange(value) {
        // 重置答案
        this.question.answer = ''
        this.question.answerList = []
      },

      // 保存或更新题目
      saveOrUpdate() {
        ////debugger
        this.$refs.questionForm.validate(valid => {
          if (valid) {
            ////debugger
            this.saveBtnDisabled = true
            
            // 处理多选题答案
            if (this.question.questionType === 2) {
              this.question.answer = this.question.answerList.join(',')
            }
            
            if (!this.question.id) {
              this.save()
            } else {
              this.update()
            }
          }
        })
      },

      // 保存题目
      save() {
        ////debugger
        questionApi.save(this.question).then(response => {
          this.$message({
            type: 'success',
            message: '题目添加成功'
          })
          this.$router.push({ path: '/question/list' })
        }).catch(response => {
          this.$message({
            type: 'error',
            message: '题目添加失败'
          })
          this.saveBtnDisabled = false
        })
      },

      // 更新题目
      update() {
        questionApi.update(this.question).then(response => {
          this.$message({
            type: 'success',
            message: '题目修改成功'
          })
          this.$router.push({ path: '/question/list' })
        }).catch(response => {
          this.$message({
            type: 'error',
            message: '题目修改失败'
          })
          this.saveBtnDisabled = false
        })
      }
    }
  }
</script>

<style scoped>
  .el-form-item__content {
    text-align: left;
  }
</style>